<script setup lang="ts">
import {ref, onMounted} from 'vue'
import {PageData} from "@/ts/CommonTypes";
import * as apiUtil from "@/api/ApiUtils"
import {deleteById, queryList, exportList, Role, RoleQuery} from "@/api/AuthRoleApi"
import Form from "./form.vue"
import {
  DownloadOutlined,
  SearchOutlined,
  PlusOutlined,
  RedoOutlined,
  FormOutlined,
  DeleteOutlined,
  ClusterOutlined,
} from "@ant-design/icons-vue"
import MenuButtonSelector from "@/components/MenuButtonSelector.vue"
import * as authUtil from "@/ts/AuthUtils";

/**
 * 当前选中的id
 */
const currentId = ref<number | null>(null);

/**
 * 查询对象
 */
const query = ref<RoleQuery>(new RoleQuery());

/**
 * 分页数据
 */
const pageData = ref<PageData<Role>>(new PageData<Role>());

/**
 * 表格展示列
 */
const columns = [
  {title: '角色名称', dataIndex: 'name', key: 'name',align:"center"},
  {title: '角色描述', dataIndex: 'description', key: 'description', width: 200, ellipsis: true},
  {title: '数据范围', dataIndex: 'dataScopeStr', key: 'dataScopeStr',align:"center"},
  {title: '创建人', dataIndex: 'createName', key: 'createName',align:"center"},
  {title: '创建时间', dataIndex: 'createTime', key: 'createTime',align:"center"},
  {title: '修改人', dataIndex: 'updateName', key: 'updateName',align:"center"},
  {title: '修改时间', dataIndex: 'updateTime', key: 'updateTime',align:"center"},
  {title: '操作', key: 'actionColumn',align:"center"}
];

/**
 * 模式
 */
const mode = ref({
  edit: false,
  delete: false,
  authorize: false
});

/**
 * 分页大小选项
 */
const pageSizeOptions = ["10", "20", "50", "100"];

/**
 * 页面加载后执行的钩子函数
 */
onMounted(() => {
  handleQueryList()
})

/**
 * 查询列表
 */
const handleQueryList = async () => {
  try {
    const res = await queryList(query.value)
    if (apiUtil.isSuccessed(res)) {
      pageData.value = res.data;
    }
  } catch (error) {
    apiUtil.notifyError('查询失败', error.message);
  }
}

/**
 * 删除数据
 */
const handleDelete = async () => {
  try {
    const res = await deleteById(currentId.value!)
    if (apiUtil.isSuccessed(res)) {
      apiUtil.notifySuccess('删除成功');
      mode.value.delete = false
      await handleQueryList()
    }
  } catch (error) {
    apiUtil.notifyError('删除失败', error.message);
  }
}

/**
 * 更改模式，控制添加、修改、删除的弹框
 * @param modeValue
 * @param id
 */
function updateMode(modeValue: "edit" | "delete" | "review", id = null) {
  currentId.value = id;
  switch (modeValue) {
    case "delete":
      mode.value.delete = true;
      break
    case "edit":
      mode.value.edit = true;
      break;
    default:
      break;
  }
}

/**
 * 取消模式的变更
 */
const handleCancel = () => {
  mode.value.edit = false
  mode.value.delete = false
  currentId.value = null
}

/**
 * 分页参数改变
 * @param current
 * @param size
 */
const handlePageChange = (current: number, size: number) => {
  query.value.size = size;
  query.value.current = current
  handleQueryList();
}

/**
 * 重置查询条件
 */
const handleCleanQuery = () => {
  query.value = new RoleQuery();
  handleQueryList()
}

/**
 * 导出数据
 */
const handleExport = () => {
  exportList(query.value)
}
</script>

<template>
  <main class="page-main">
    <!-- 查询 -->
    <div class="padding-20">
      <a-row>
        <!-- 查询条件 -->
        <a-col :span="18">
          <a-form  :label-col="{ style: { width: '80px' } }"
                  :model="query" autocomplete="off">
            <a-row>
              <a-col :span="8">
                <a-form-item label="角色名称" name="phone">
                  <a-input class="width" v-model:value="query.name"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <!-- 查询按钮 -->
        <a-col :span="6">
          <div class="text-right">
            <a-space size="large">
              <a-button type="default" @click="handleCleanQuery">
                <template #icon>
                  <RedoOutlined/>
                </template>
                重置
              </a-button>
              <a-button type="primary" @click="handleQueryList">
                <template #icon>
                  <SearchOutlined/>
                </template>
                查询
              </a-button>
              <a-button v-if="authUtil.permit('exportAuthRole')"
                        type="dashed" @click="handleExport">
                <template #icon>
                  <DownloadOutlined/>
                </template>
                导出
              </a-button>
            </a-space>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 分隔线 -->
    <div class="space"></div>
    <!-- 表格 -->
    <div class="padding-20">
      <div class="text-right margin-bottom-20">
        <a-button v-if="authUtil.permit('addAuthRole')"
                  type="primary" @click="updateMode('edit')">
          <template #icon>
            <PlusOutlined/>
          </template>
          添加
        </a-button>
      </div>
      <a-table
          bordered
          :columns="columns"
          :data-source="pageData.records"
          :pagination="false"
          class="ant-table-striped"
          :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actionColumn'">
            <a-flex class="width" justify="space-around" v-if="record.id > 1">
              <a-tooltip title="修改" v-if="authUtil.permit('editAuthRole')">
                <a-button type="text" size="small" class="button-edit" @click="updateMode('edit',record.id)">
                  <template #icon>
                    <FormOutlined/>
                  </template>
                  修改
                </a-button>
              </a-tooltip>

              <a-tooltip title="删除" v-if="authUtil.permit('deleteAuthRole')">
                <a-button type="text" size="small" class="button-delete" @click="updateMode('delete',record.id)">
                  <template #icon>
                    <DeleteOutlined/>
                  </template>
                  删除
                </a-button>
              </a-tooltip>
              <a-tooltip title="赋权" v-if="authUtil.permit('authByAuthRole')">
                <a-button type="text" size="small" @click="currentId=record.id; mode.authorize=true">
                  <template #icon>
                    <ClusterOutlined/>
                  </template>
                  权限设置
                </a-button>
              </a-tooltip>
            </a-flex>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="float-right margin-10-20">
        <a-pagination
            v-model:current="query.current"
            :total="pageData.total"
            show-size-changer
            :page-size-options="pageSizeOptions"
            @showSizeChange="handlePageChange"
            @change="handlePageChange"
        />
      </div>
      <!-- 清理浮动 -->
      <div class="clear"></div>
    </div>

    <!-- 新增、编辑的表单页 -->
    <a-drawer v-model:open="mode.edit" :title="currentId ? '修改角色' : '添加角色'" size="large">
      <Form :dataId="currentId" @close="handleCancel" @successed="handleQueryList" :key="new Date().getTime()"/>
    </a-drawer>

    <!-- 赋权的操作页 -->
    <a-drawer size="large" v-model:open="mode.authorize">
      <MenuButtonSelector :roleId="currentId" :key="new Date().getTime()" @close="mode.authorize=false"/>
    </a-drawer>

    <!-- 删除提示框 -->
    <a-modal v-model:open="mode.delete" title="确定删除">
      <span>确定删除角色吗？删除后数据不可恢复</span>
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" danger @click="handleDelete">删除</a-button>
      </template>
    </a-modal>
  </main>
</template>

<style scoped>
/* 斑马纹表格样式 */
.ant-table-striped :deep(.table-striped) td {
  background-color: #f5f5f5;
}
</style>
